/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JIFCertificado.java
 *
 * Created on 05/10/2011, 10:00:30
 */
package view.admin;

import util.TitularComboModel;
import control.CertificadoControl;
import java.awt.Color;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.swing.JFormattedTextField;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.table.TableCellRenderer;
import javax.swing.text.MaskFormatter;
import model.Certificado;
import model.EntidadeSimpleFactory;
import model.Pessoa;
import util.CellRenderer;
import view.IJIFSimpleFactory;

/**
 *
 * @author Felipe
 */
public class JIFCertificado extends JInternalFrame implements IJIFSimpleFactory {

    private CertificadoControl controller;    
    private boolean alterar, alterado;
    private int id;
    private MaskFormatter mskExp, mskVen;    
    private String strCertificadora, strCategoria;
    private TitularComboModel titularComboModel;
    
    /** Creates new form JIFCertificado */
    public JIFCertificado() {
        id = 0;        
        controller = CertificadoControl.getInstance();
        alterar = false;
        strCertificadora = "";
        strCategoria = "";
        titularComboModel = new TitularComboModel(controller.getListPessoa());        
        initComponents();        
        btgCategoria.add(rbtnA1);
        btgCategoria.add(rbtnA3);
        btgCertificadora.add(rbtnSerasa);
        btgCertificadora.add(rbtnSerpro);
        limparRbtns();
        txtBusca.setFocusable(true);
        selecionarAba(0);        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        btgCategoria = new javax.swing.ButtonGroup();
        btgCertificadora = new javax.swing.ButtonGroup();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        pnlLista = new javax.swing.JPanel();
        pnlSul = new javax.swing.JPanel();
        pnlSuperior = new javax.swing.JPanel();
        pnlBusca = new javax.swing.JPanel();
        cbbModoBusca = new javax.swing.JComboBox();
        cbbBusca = new javax.swing.JComboBox();
        btnBuscar = new javax.swing.JButton();
        txtBusca = new javax.swing.JTextField();
        pnlJtb = new javax.swing.JPanel();
        jtbSuperior = new javax.swing.JToolBar();
        btnIncluir = new javax.swing.JButton();
        btnVisualisar = new javax.swing.JButton();
        btnRemover = new javax.swing.JButton();
        pnlSuperiorCentro = new javax.swing.JPanel();
        pnlSuperiorCentroDivisor = new javax.swing.JPanel();
        pnlLeste = new javax.swing.JPanel();
        pnlOeste = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblCertificado = new javax.swing.JTable();
        pnlCadBasico = new javax.swing.JPanel();
        pnlCamposCadastro = new javax.swing.JPanel();
        pnlForm = new javax.swing.JPanel();
        lblTitular = new javax.swing.JLabel();
        cbbTitular = new javax.swing.JComboBox();
        lblSegmento = new javax.swing.JLabel();
        cbbSegmento = new javax.swing.JComboBox();
        rbtnA1 = new javax.swing.JRadioButton();
        rbtnA3 = new javax.swing.JRadioButton();
        lblCategoria = new javax.swing.JLabel();
        lblMidia = new javax.swing.JLabel();
        cbbMidia = new javax.swing.JComboBox();
        lblCertificadora = new javax.swing.JLabel();
        rbtnSerpro = new javax.swing.JRadioButton();
        rbtnSerasa = new javax.swing.JRadioButton();
        lblExpedicao = new javax.swing.JLabel();
        try
        {
            // Cria o formato da mascara
            mskExp = new MaskFormatter("##/##/####");  

            // Define o tipo de caracter onde será inserido o texto
            mskExp.setPlaceholderCharacter('_');
        }   
        catch (ParseException excp)
        {
        }
        ftxtExpedicao = new JFormattedTextField(mskExp);  ;
        lblVencimento = new javax.swing.JLabel();
        try
        {
            // Cria o formato da mascara
            mskVen = new MaskFormatter("##/##/####");  

            // Define o tipo de caracter onde será inserido o texto
            mskVen.setPlaceholderCharacter('_');
        }   
        catch (ParseException excp)
        {
        }
        ftxtVencimento = new JFormattedTextField(mskVen);  ;
        pnlBotoes = new javax.swing.JPanel();
        btnGravar = new javax.swing.JButton();
        btnVoltar = new javax.swing.JButton();

        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setIconifiable(true);
        setTitle("Controle de certificados digitais");
        setPreferredSize(new java.awt.Dimension(765, 582));
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        pnlLista.setLayout(new java.awt.BorderLayout());
        pnlLista.add(pnlSul, java.awt.BorderLayout.SOUTH);

        pnlSuperior.setMinimumSize(new java.awt.Dimension(364, 50));
        pnlSuperior.setLayout(new java.awt.BorderLayout());

        pnlBusca.setLayout(new javax.swing.BoxLayout(pnlBusca, javax.swing.BoxLayout.LINE_AXIS));

        cbbModoBusca.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Todos", "Válidos", "Vencidos" }));
        cbbModoBusca.setMaximumSize(new java.awt.Dimension(170, 20));
        cbbModoBusca.setMinimumSize(new java.awt.Dimension(170, 20));
        cbbModoBusca.setPreferredSize(new java.awt.Dimension(170, 20));
        cbbModoBusca.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbbModoBuscaActionPerformed(evt);
            }
        });
        pnlBusca.add(cbbModoBusca);

        cbbBusca.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Titular", "Segmento", "Categoria", "Mídia", "Certificadora" }));
        cbbBusca.setMaximumSize(new java.awt.Dimension(120, 20));
        cbbBusca.setMinimumSize(new java.awt.Dimension(120, 20));
        cbbBusca.setPreferredSize(new java.awt.Dimension(120, 20));
        pnlBusca.add(cbbBusca);

        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/i16x16/buscar2.png"))); // NOI18N
        btnBuscar.setToolTipText("Procurar");
        btnBuscar.setMaximumSize(new java.awt.Dimension(30, 20));
        btnBuscar.setMinimumSize(new java.awt.Dimension(30, 20));
        btnBuscar.setOpaque(false);
        btnBuscar.setPreferredSize(new java.awt.Dimension(30, 20));
        pnlBusca.add(btnBuscar);

        txtBusca.setMaximumSize(new java.awt.Dimension(200, 20));
        txtBusca.setMinimumSize(new java.awt.Dimension(200, 20));
        txtBusca.setPreferredSize(new java.awt.Dimension(200, 20));
        txtBusca.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtBuscaKeyPressed(evt);
            }
        });
        pnlBusca.add(txtBusca);

        pnlSuperior.add(pnlBusca, java.awt.BorderLayout.EAST);

        pnlJtb.setLayout(new java.awt.BorderLayout());

        jtbSuperior.setBorder(null);
        jtbSuperior.setFloatable(false);
        jtbSuperior.setRollover(true);
        jtbSuperior.setOpaque(false);

        btnIncluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/i16x16/inserir.png"))); // NOI18N
        btnIncluir.setToolTipText("Inclur registro");
        btnIncluir.setFocusable(false);
        btnIncluir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnIncluir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jtbSuperior, org.jdesktop.beansbinding.ELProperty.create("false"), btnIncluir, org.jdesktop.beansbinding.BeanProperty.create("borderPainted"));
        bindingGroup.addBinding(binding);

        btnIncluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIncluirActionPerformed(evt);
            }
        });
        jtbSuperior.add(btnIncluir);

        btnVisualisar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/i16x16/view1.gif"))); // NOI18N
        btnVisualisar.setToolTipText("Visualizar registro");
        btnVisualisar.setFocusable(false);
        btnVisualisar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnVisualisar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jtbSuperior, org.jdesktop.beansbinding.ELProperty.create("false"), btnVisualisar, org.jdesktop.beansbinding.BeanProperty.create("borderPainted"));
        bindingGroup.addBinding(binding);

        btnVisualisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVisualisarActionPerformed(evt);
            }
        });
        jtbSuperior.add(btnVisualisar);

        btnRemover.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/i16x16/remover.png"))); // NOI18N
        btnRemover.setToolTipText("Remover registro");
        btnRemover.setFocusable(false);
        btnRemover.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnRemover.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jtbSuperior, org.jdesktop.beansbinding.ELProperty.create("false"), btnRemover, org.jdesktop.beansbinding.BeanProperty.create("borderPainted"));
        bindingGroup.addBinding(binding);

        btnRemover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoverActionPerformed(evt);
            }
        });
        jtbSuperior.add(btnRemover);

        pnlJtb.add(jtbSuperior, java.awt.BorderLayout.CENTER);

        pnlSuperior.add(pnlJtb, java.awt.BorderLayout.WEST);

        pnlSuperiorCentro.setMaximumSize(new java.awt.Dimension(364, 50));
        pnlSuperiorCentro.setPreferredSize(new java.awt.Dimension(613, 50));
        pnlSuperiorCentro.setLayout(new javax.swing.BoxLayout(pnlSuperiorCentro, javax.swing.BoxLayout.LINE_AXIS));

        pnlSuperiorCentroDivisor.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        pnlSuperiorCentroDivisor.setMaximumSize(new java.awt.Dimension(1000, 20));
        pnlSuperiorCentroDivisor.setOpaque(false);
        pnlSuperiorCentroDivisor.setPreferredSize(new java.awt.Dimension(1000, 20));
        pnlSuperiorCentro.add(pnlSuperiorCentroDivisor);

        pnlSuperior.add(pnlSuperiorCentro, java.awt.BorderLayout.CENTER);

        pnlLista.add(pnlSuperior, java.awt.BorderLayout.PAGE_START);
        pnlLista.add(pnlLeste, java.awt.BorderLayout.EAST);
        pnlLista.add(pnlOeste, java.awt.BorderLayout.WEST);

        tblCertificado.setAutoCreateRowSorter(true);
        tblCertificado.setModel(controller.getTableModel());
        tblCertificado.setRowHeight(20);
        ajustarTamanhoColunas();
        jScrollPane1.setViewportView(tblCertificado);

        pnlLista.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jTabbedPane1.addTab("Lista", pnlLista);

        pnlCadBasico.setLayout(new java.awt.BorderLayout());

        lblTitular.setText("Titular");

        cbbTitular.setModel(titularComboModel);
        cbbTitular.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                cbbTitularMousePressed(evt);
            }
        });

        lblSegmento.setText("Segmento");

        cbbSegmento.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "eCPF", "eCNPJ", "eCNPJ ME EPP" }));
        cbbSegmento.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                cbbSegmentoMousePressed(evt);
            }
        });

        rbtnA1.setText("A1");
        rbtnA1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbtnA1ActionPerformed(evt);
            }
        });

        rbtnA3.setText("A3");
        rbtnA3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbtnA3ActionPerformed(evt);
            }
        });

        lblCategoria.setText("Categoria");

        lblMidia.setText("Mídia");

        cbbMidia.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Arquivo", "Cartao", "Token" }));
        cbbMidia.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                cbbMidiaMousePressed(evt);
            }
        });

        lblCertificadora.setText("Certificadora");

        rbtnSerpro.setText("Serpro/Correios");
        rbtnSerpro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbtnSerproActionPerformed(evt);
            }
        });

        rbtnSerasa.setText("Serasa");
        rbtnSerasa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbtnSerasaActionPerformed(evt);
            }
        });

        lblExpedicao.setText("Data de Expedição");

        formatador1 = new SimpleDateFormat("dd/MM/yyyy");
        formatador1.setLenient(false);
        ftxtExpedicao.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);
        ftxtExpedicao.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                ftxtExpedicaoCaretUpdate(evt);
            }
        });
        ftxtExpedicao.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                ftxtExpedicaoFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                ftxtExpedicaoFocusLost(evt);
            }
        });
        ftxtExpedicao.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                ftxtExpedicaoKeyPressed(evt);
            }
        });

        lblVencimento.setText("Data de Vencimento");

        formatador2 = new SimpleDateFormat("dd/MM/yyyy");
        formatador2.setLenient(false);
        ftxtVencimento.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);
        ftxtVencimento.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                ftxtVencimentoCaretUpdate(evt);
            }
        });
        ftxtVencimento.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                ftxtVencimentoFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                ftxtVencimentoFocusLost(evt);
            }
        });
        ftxtVencimento.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                ftxtVencimentoKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout pnlFormLayout = new javax.swing.GroupLayout(pnlForm);
        pnlForm.setLayout(pnlFormLayout);
        pnlFormLayout.setHorizontalGroup(
            pnlFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlFormLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblVencimento)
                    .addComponent(lblExpedicao)
                    .addComponent(lblCertificadora)
                    .addComponent(lblMidia)
                    .addComponent(lblCategoria)
                    .addComponent(lblSegmento)
                    .addComponent(lblTitular))
                .addGap(18, 18, 18)
                .addGroup(pnlFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cbbTitular, javax.swing.GroupLayout.PREFERRED_SIZE, 257, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(pnlFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(ftxtVencimento, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(ftxtExpedicao, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 91, Short.MAX_VALUE))
                    .addGroup(pnlFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(cbbSegmento, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(cbbMidia, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, pnlFormLayout.createSequentialGroup()
                            .addGroup(pnlFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(rbtnSerpro)
                                .addComponent(rbtnA1))
                            .addGap(9, 9, 9)
                            .addGroup(pnlFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(rbtnSerasa)
                                .addComponent(rbtnA3)))))
                .addGap(40, 40, 40))
        );
        pnlFormLayout.setVerticalGroup(
            pnlFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlFormLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cbbTitular, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblTitular))
                .addGap(3, 3, 3)
                .addGroup(pnlFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblSegmento)
                    .addComponent(cbbSegmento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(rbtnA1)
                    .addComponent(lblCategoria)
                    .addComponent(rbtnA3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblMidia)
                    .addComponent(cbbMidia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(rbtnSerpro)
                    .addComponent(lblCertificadora)
                    .addComponent(rbtnSerasa))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(pnlFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ftxtExpedicao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblExpedicao))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ftxtVencimento, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblVencimento))
                .addContainerGap(17, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout pnlCamposCadastroLayout = new javax.swing.GroupLayout(pnlCamposCadastro);
        pnlCamposCadastro.setLayout(pnlCamposCadastroLayout);
        pnlCamposCadastroLayout.setHorizontalGroup(
            pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlCamposCadastroLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnlForm, javax.swing.GroupLayout.PREFERRED_SIZE, 421, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(366, Short.MAX_VALUE))
        );
        pnlCamposCadastroLayout.setVerticalGroup(
            pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlCamposCadastroLayout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(pnlForm, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(241, Short.MAX_VALUE))
        );

        pnlCadBasico.add(pnlCamposCadastro, java.awt.BorderLayout.CENTER);

        pnlBotoes.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        btnGravar.setText("Gravar");
        btnGravar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGravarActionPerformed(evt);
            }
        });

        btnVoltar.setText("Voltar");
        btnVoltar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVoltarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlBotoesLayout = new javax.swing.GroupLayout(pnlBotoes);
        pnlBotoes.setLayout(pnlBotoesLayout);
        pnlBotoesLayout.setHorizontalGroup(
            pnlBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlBotoesLayout.createSequentialGroup()
                .addContainerGap(601, Short.MAX_VALUE)
                .addComponent(btnGravar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnVoltar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        pnlBotoesLayout.setVerticalGroup(
            pnlBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlBotoesLayout.createSequentialGroup()
                .addGroup(pnlBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnVoltar)
                    .addComponent(btnGravar))
                .addContainerGap(22, Short.MAX_VALUE))
        );

        pnlCadBasico.add(pnlBotoes, java.awt.BorderLayout.PAGE_END);

        jTabbedPane1.addTab("Informações básicas", pnlCadBasico);

        getContentPane().add(jTabbedPane1, java.awt.BorderLayout.PAGE_START);

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnIncluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIncluirActionPerformed
        setCamposEnabled(true);
        selecionarAba(1);        
    }//GEN-LAST:event_btnIncluirActionPerformed

    private void btnGravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGravarActionPerformed
        gravarCertificado();         
    }//GEN-LAST:event_btnGravarActionPerformed

    private void ftxtExpedicaoCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_ftxtExpedicaoCaretUpdate
        liberarBtnGravar();
    }//GEN-LAST:event_ftxtExpedicaoCaretUpdate

    private void ftxtVencimentoCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_ftxtVencimentoCaretUpdate
        liberarBtnGravar();
    }//GEN-LAST:event_ftxtVencimentoCaretUpdate

    private void btnRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoverActionPerformed
        removerCertificado();
    }//GEN-LAST:event_btnRemoverActionPerformed

    private void txtBuscaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscaKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {                      
             buscar();
         } 
    }//GEN-LAST:event_txtBuscaKeyPressed

    private void btnVisualisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVisualisarActionPerformed
        visualizarCertificado();
    }//GEN-LAST:event_btnVisualisarActionPerformed

    private void ftxtExpedicaoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_ftxtExpedicaoFocusGained
        ftxtExpedicao.setBackground(new Color(255,255,220));
    }//GEN-LAST:event_ftxtExpedicaoFocusGained

    private void ftxtExpedicaoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_ftxtExpedicaoFocusLost
        ftxtExpedicao.setBackground(new Color(255,255,255));
    }//GEN-LAST:event_ftxtExpedicaoFocusLost

    private void ftxtVencimentoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_ftxtVencimentoFocusGained
        ftxtVencimento.setBackground(new Color(255,255,220));
    }//GEN-LAST:event_ftxtVencimentoFocusGained

    private void ftxtVencimentoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_ftxtVencimentoFocusLost
        ftxtVencimento.setBackground(new Color(255,255,255));
    }//GEN-LAST:event_ftxtVencimentoFocusLost

    private void btnVoltarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVoltarActionPerformed
        mudarFrame();
    }//GEN-LAST:event_btnVoltarActionPerformed

    private void ftxtExpedicaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ftxtExpedicaoKeyPressed
        setAlterado(true);
    }//GEN-LAST:event_ftxtExpedicaoKeyPressed

    private void ftxtVencimentoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ftxtVencimentoKeyPressed
        setAlterado(true);
    }//GEN-LAST:event_ftxtVencimentoKeyPressed

    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
        if (getAlterado()) {
            int n = JOptionPane.showConfirmDialog(null,
                    "Deseja gravar as alterações efetuadas!",
                    "Confirmação",
                    JOptionPane.YES_NO_CANCEL_OPTION);
        
            if (n != JOptionPane.CANCEL_OPTION) {
                if (n == JOptionPane.YES_OPTION) {
                    
                    dispose();
                } else {
                    dispose();
                }
            }             
        } else {
            dispose();
        }
    }//GEN-LAST:event_formInternalFrameClosing

    private void cbbTitularMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cbbTitularMousePressed
        setAlterado(true);
    }//GEN-LAST:event_cbbTitularMousePressed

    private void cbbSegmentoMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cbbSegmentoMousePressed
        setAlterado(true);
    }//GEN-LAST:event_cbbSegmentoMousePressed

    private void cbbMidiaMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cbbMidiaMousePressed
        setAlterado(true);
    }//GEN-LAST:event_cbbMidiaMousePressed

    private void rbtnA1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbtnA1ActionPerformed
        setAlterado(true);
        liberarBtnGravar();
        setStrCategoria("A1");
    }//GEN-LAST:event_rbtnA1ActionPerformed

    private void rbtnA3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbtnA3ActionPerformed
        setAlterado(true);
        liberarBtnGravar();
        setStrCategoria("A3");
    }//GEN-LAST:event_rbtnA3ActionPerformed

    private void rbtnSerproActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbtnSerproActionPerformed
        setAlterado(true);
        liberarBtnGravar();
        setStrCertificadora("SERPRO");
    }//GEN-LAST:event_rbtnSerproActionPerformed

    private void rbtnSerasaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbtnSerasaActionPerformed
        setAlterado(true);
        liberarBtnGravar();
        setStrCertificadora("SERASA");
    }//GEN-LAST:event_rbtnSerasaActionPerformed

    private void cbbModoBuscaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbbModoBuscaActionPerformed
        switch (cbbModoBusca.getSelectedIndex()) {
            case 0: 
                controller.alterarModoTableModel(0);
                break;
            case 1: 
                controller.alterarModoTableModel(1);
                break;
            case 2:
                controller.alterarModoTableModel(2);
                break;
        }
    }//GEN-LAST:event_cbbModoBuscaActionPerformed

    private void mudarFrame() {
        if (getAlterado()) {
            int n = JOptionPane.showConfirmDialog(null,
                    "Deseja gravar as alterações efetuadas!",
                    "Confirmação",
                    JOptionPane.YES_NO_CANCEL_OPTION);
        
            if (n != JOptionPane.CANCEL_OPTION) {
                if (n == JOptionPane.YES_OPTION) {
                                        
                    setAlterado(false);
                } else {
                    selecionarAba(0);
                    setAlterado(false);
                    limparCampos();
                }
            }             
        } else {
            limparCampos();            
            selecionarAba(0);            
        }       
    }    
    
    private void buscar() {
        //controller.buscar(txtBusca.getText(), cbbBusca.getSelectedIndex());
    }
    /**
     * Este método foi feito para facilitar a leitura do código.<br>
     * Ele retorna o índice da linha orientado a zero e em qualquer ordem de apresentação.
     * @return int linha selecionada  
     */
    private int getLinha() {
        return tblCertificado.convertRowIndexToModel(tblCertificado.getSelectedRow());
    }
    
    private void limparCampos() {
        cbbTitular.setSelectedIndex(0);
        cbbSegmento.setSelectedIndex(0);
        cbbMidia.setSelectedIndex(0);
        limparRbtns();
        ftxtExpedicao.setText("");
        ftxtVencimento.setText("");        
    }
    
    private void popularCampos() {
        Certificado certificado = controller.getTableModel().getCertificado(getLinha());
        cbbTitular.setSelectedItem(certificado.getTitular());
        cbbSegmento.setSelectedItem(certificado.getSegmento());
        
        // Selecionar categoria sem usar polimorfismo
        if (certificado.getCategoria().equals("A1")) {
            rbtnA1.setSelected(true);
        } else {
            rbtnA3.setSelected(true);
        }
        
        cbbMidia.setSelectedItem(certificado.getMidia());
        
        if (certificado.getCertificadora().equals("SERPRO")) {
            rbtnSerpro.setSelected(true);
        } else {
            rbtnSerasa.setSelected(true);
        }
        
        ftxtExpedicao.setText(formatador1.format(certificado.getExpedicao().getTimeInMillis()));
        ftxtVencimento.setText(formatador1.format(certificado.getVencimento().getTimeInMillis()));       
                
        setId(certificado.getId());        
        selecionarAba(1);
    }
    
    private void visualizarCertificado() {
        popularCampos();
        setCamposEnabled(false);
        selecionarAba(1);
    }
        
    private void liberarBtnGravar() {
        if (
                (!ftxtExpedicao.getText().endsWith("_")) &&               
                (!ftxtVencimento.getText().endsWith("_")) &&
                ((rbtnA1.isSelected() == true) || (rbtnA3.isSelected() == true)) &&
                ((rbtnSerpro.isSelected() == true) || (rbtnSerasa.isSelected() == true))
            ) 
        {
            btnGravar.setEnabled(true);
        } else
        {
            btnGravar.setEnabled(false);
        }       
    }
    
    private Certificado atualizarCertificado(Certificado certificado) throws Exception  {
        // Atualiza o objeto
        certificado.setTitular((Pessoa)cbbTitular.getSelectedItem());
        certificado.setSegmento((String)cbbSegmento.getSelectedItem());
        certificado.setCategoria(getStrCategoria());
        certificado.setMidia((String)cbbMidia.getSelectedItem());        
        certificado.setCertificadora(getStrCertificadora());
               
        try {
            Date data = formatador1.parse(ftxtExpedicao.getText());
            Calendar calExp = new GregorianCalendar();
            calExp.setTime(data);
            certificado.setExpedicao(calExp);
        } catch (ParseException ex) {
           throw new Exception("Data de expedição inconsistente!");
        }
        
        try {
            Date data = formatador2.parse(ftxtVencimento.getText());
            Calendar calVen = new GregorianCalendar();
            calVen.setTime(data);
            certificado.setVencimento(calVen);
        } catch (ParseException ex) {
           throw new Exception("Data de vencimento inconsistente!");
        }
        
        setAlterado(false);
        return certificado;
    }
    
    private void gravarCertificado() {
        try {
            Certificado certificado = (Certificado) EntidadeSimpleFactory.getEntity(Certificado.class);
            controller.addCertificado(atualizarCertificado(certificado));
            JOptionPane.showMessageDialog(null, "Registro gravado com sucesso!");
            limparCampos();
            selecionarAba(0);                  
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }                     
                
    private void removerCertificado() {
        JOptionPane.showMessageDialog(null, 
                    "Não é recomendado excluir um certificado a não ser que a criação do\n"+
                    "mesmo tenha sido feita de forma incorreta! \n" +
                    "É interessante manter o registro dos certificados mesmo vencidos\n"+ 
                    "para fins de controle e estatística.\n"
                );
        int n = JOptionPane.showConfirmDialog(null,
                    "Esta operação não poderá ser desfeita!\n" +
                    "Deseja realmente excluir este registro?\n",
                    "Exclusão de registro",
                    JOptionPane.YES_NO_OPTION);
        
        if (n == JOptionPane.YES_OPTION) {
            try {
                controller.removerCertificado(getLinha());
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
            }
        }        
    }    
    
    private void ajustarTamanhoColunas() {
        // Centralizar conteudo da células
        TableCellRenderer tcr = new CellRenderer();  
        tblCertificado.getColumnModel().getColumn(1).setCellRenderer(tcr);
        tblCertificado.getColumnModel().getColumn(2).setCellRenderer(tcr);
        tblCertificado.getColumnModel().getColumn(3).setCellRenderer(tcr);
        tblCertificado.getColumnModel().getColumn(4).setCellRenderer(tcr);
        tblCertificado.getColumnModel().getColumn(5).setCellRenderer(tcr);
        tblCertificado.getColumnModel().getColumn(6).setCellRenderer(tcr);
        tblCertificado.getColumnModel().getColumn(7).setCellRenderer(tcr);
        
        tblCertificado.getColumnModel().getColumn(0).setPreferredWidth(250);
        tblCertificado.getColumnModel().getColumn(1).setPreferredWidth(60);
        tblCertificado.getColumnModel().getColumn(2).setPreferredWidth(50);
        tblCertificado.getColumnModel().getColumn(3).setPreferredWidth(50);
        tblCertificado.getColumnModel().getColumn(4).setPreferredWidth(60);
        tblCertificado.getColumnModel().getColumn(5).setPreferredWidth(70);
        tblCertificado.getColumnModel().getColumn(6).setPreferredWidth(70);
        tblCertificado.getColumnModel().getColumn(7).setPreferredWidth(70);
    }
   
    private void selecionarAba(int aba) {
        switch (aba) {
            case 0 :    jTabbedPane1.setSelectedIndex(0);
                        limparRbtns();
                        jTabbedPane1.setEnabledAt(0, true);
                        jTabbedPane1.setEnabledAt(1, false);
                        break;
                
            case 1 :    jTabbedPane1.setSelectedIndex(1); 
                        jTabbedPane1.setEnabledAt(0, false);
                        jTabbedPane1.setEnabledAt(1, true);
                        break;           
        }
    }
    
    private void limparRbtns() {
        btgCategoria.clearSelection();
        btgCertificadora.clearSelection();
        setStrCategoria("");
        setStrCertificadora("");
    }
    
    private void setCamposEnabled(boolean ativo) {
        if (ativo == true) {
            cbbTitular.setEnabled(true);
            cbbSegmento.setEnabled(true);
            rbtnA1.setEnabled(true);
            rbtnA3.setEnabled(true);
            cbbMidia.setEnabled(true);
            rbtnSerpro.setEnabled(true);
            rbtnSerasa.setEnabled(true);
            ftxtExpedicao.setEnabled(true);
            ftxtVencimento.setEnabled(true);
            btnGravar.setVisible(true);
        } else {
            cbbTitular.setEnabled(false);
            cbbSegmento.setEnabled(false);
            rbtnA1.setEnabled(false);
            rbtnA3.setEnabled(false);
            cbbMidia.setEnabled(false);
            rbtnSerpro.setEnabled(false);
            rbtnSerasa.setEnabled(false);
            ftxtExpedicao.setEnabled(false);
            ftxtVencimento.setEnabled(false);
            btnGravar.setVisible(false);
        }
    }
    
    // Getters and setters
    //private void setAlterar(boolean alterar) { this.alterar = alterar; }
    //private boolean isAlterar() { return this.alterar; }
    private void setId(int id) { this.id = id; }
    private int getId() { return this.id; }
    private void setAlterado(boolean alterado) { this.alterado = alterado; }
    private boolean getAlterado() { return this.alterado; }
    private String getStrCertificadora() { return strCertificadora; }
    private void setStrCertificadora(String strCertificadora) { this.strCertificadora = strCertificadora; }
    private String getStrCategoria() { return strCategoria; }
    private void setStrCategoria(String strCategoria) { this.strCategoria = strCategoria; }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup btgCategoria;
    private javax.swing.ButtonGroup btgCertificadora;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnGravar;
    private javax.swing.JButton btnIncluir;
    private javax.swing.JButton btnRemover;
    private javax.swing.JButton btnVisualisar;
    private javax.swing.JButton btnVoltar;
    private javax.swing.JComboBox cbbBusca;
    private javax.swing.JComboBox cbbMidia;
    private javax.swing.JComboBox cbbModoBusca;
    private javax.swing.JComboBox cbbSegmento;
    private javax.swing.JComboBox cbbTitular;
    private SimpleDateFormat formatador1;
    private javax.swing.JFormattedTextField ftxtExpedicao;
    private SimpleDateFormat formatador2;
    private javax.swing.JFormattedTextField ftxtVencimento;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JToolBar jtbSuperior;
    private javax.swing.JLabel lblCategoria;
    private javax.swing.JLabel lblCertificadora;
    private javax.swing.JLabel lblExpedicao;
    private javax.swing.JLabel lblMidia;
    private javax.swing.JLabel lblSegmento;
    private javax.swing.JLabel lblTitular;
    private javax.swing.JLabel lblVencimento;
    private javax.swing.JPanel pnlBotoes;
    private javax.swing.JPanel pnlBusca;
    private javax.swing.JPanel pnlCadBasico;
    private javax.swing.JPanel pnlCamposCadastro;
    private javax.swing.JPanel pnlForm;
    private javax.swing.JPanel pnlJtb;
    private javax.swing.JPanel pnlLeste;
    private javax.swing.JPanel pnlLista;
    private javax.swing.JPanel pnlOeste;
    private javax.swing.JPanel pnlSul;
    private javax.swing.JPanel pnlSuperior;
    private javax.swing.JPanel pnlSuperiorCentro;
    private javax.swing.JPanel pnlSuperiorCentroDivisor;
    private javax.swing.JRadioButton rbtnA1;
    private javax.swing.JRadioButton rbtnA3;
    private javax.swing.JRadioButton rbtnSerasa;
    private javax.swing.JRadioButton rbtnSerpro;
    private javax.swing.JTable tblCertificado;
    private javax.swing.JTextField txtBusca;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
